<template>
  <div class="app-container">
    <!-- 搜索、排序…… -->
    <div class="filter-container">
      <!-- 名 -->
      <el-input v-model="listQuery.name" placeholder="Name" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />&nbsp;
      
      <!-- 类别 -->
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 150px">
         <el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>&nbsp;
      
      <!-- 礼品状态 -->
      <el-select v-model="listQuery.status" placeholder="Status" clearable class="filter-item" style="width: 150px">
        <el-option v-for="item in statusOptions" :key="item" :label="item" :value="item" />
      </el-select>&nbsp;
      
      <!-- 升序/降序 -->
      <el-select v-model="listQuery.sort" style="width: 150px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>&nbsp;
      <!-- 操作 -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <!-- ID -->
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="auto" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <!-- 礼品名 -->
      <el-table-column label="Name" width="auto" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
        </template>
      </el-table-column>
      
      <!-- 数量 -->
      <el-table-column label="Number" min-width="auto">
        <template slot-scope="{row}">
          <span>{{ row.number }}</span>
        </template>
      </el-table-column>

      <!-- 所需积分 -->
      <el-table-column label="Point" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.point }}</span>
        </template>
      </el-table-column>

      <!-- 礼品类别 -->
      <el-table-column label="Type" width="auto" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type }}</span>
        </template>
      </el-table-column>

      <!-- 获取方式 -->
      <el-table-column label="Getway" width="auto">
        <template slot-scope="{row}">
          <span>{{ row.getway }}</span>
        </template>
      </el-table-column>

      <!-- 操作人 -->
      <el-table-column label="Operator" width="auto">
        <template slot-scope="{row}">
          <span>{{ row.operator }}</span>
        </template>
      </el-table-column>

      <!-- 更新时间 -->
      <el-table-column label="Date" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <!-- 礼品图片 -->
      <el-table-column label="Img" align="center" width="auto">
        <template slot-scope="{row}">
          <span >{{ row.img }}</span>
        </template>
      </el-table-column>

      <!-- 礼品状态 -->
      <el-table-column label="Status" class-name="status-col" width="auto">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="Actions" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            修改
          </el-button>
          <el-button v-if="row.status=='preparing'" size="mini" type="sucess" @click="handleModifyStatus(row,'inline')">
            上线
          </el-button>
          <el-button v-if="row.status=='inline'" size="mini">
            已上线
          </el-button>
          <el-button v-if="row.status=='empty'" size="mini">
            已上线
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getGiftList" />

      <!-- 修改、添加 弹框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        
        <!-- 礼品名 -->
        <el-form-item label="礼品名称" prop="name">
          <el-input v-model="temp.name" class="filter-item" placeholder="Please input"></el-input>
        </el-form-item>

        <!-- 类别 -->
        <el-form-item label="礼品类型" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="Please select">
            <el-option v-for="item in typeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>

        <!-- 获取方式 -->
        <el-form-item label="发放方式" prop="way">
          <el-select v-model="temp.getway" class="filter-item" placeholder="请选择">
            <el-option v-for="item in wayOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <!-- 所需积分 -->
        <el-form-item label="兑换积分" prop="point">
          <el-input v-model="temp.point" class="filter-item" placeholder="Please input"></el-input>
        </el-form-item>

        <!-- 数量 -->
        <el-form-item label="礼品数量" prop="number">
          <el-input v-model="temp.number" class="filter-item" placeholder="Please input"></el-input>
        </el-form-item>

        <!-- 图片 -->      
        <el-form-item label="礼品封面" prop="img">
          <Upload v-model="temp.img"></Upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createGiftData():updateGiftData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { fetchGiftList, createGift, updateGift } from '@/api/gift'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import Upload from '@/components/Upload/SingleImage'

const typeOptions = [
  { key: 'coupon', display_name: '券' },
  { key: 'real', display_name: '实物' },
  { key: 'virtual', display_name: '平台物品' }
]

const typeKeyValue = typeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.type_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination ,Upload},
  directives: { waves },
  
  filters: {
    statusFilter(status) {
      const statusMap = {
        inline: 'success',
        preparing: 'info',
        deleted: 'danger',
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        type: undefined,
        getway: undefined,
        point: undefined,
        number:undefined,
        img:undefined,
        sort: '+id'
      },
      typeOptions,
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['inline', 'preparing','empty'],
      wayOptions: ['账户发放','线下发放'],
      temp: {
        id: undefined,
        name: '',
        type:'',
        getway:'',
        point:'',
        number:'',
        img:'',
        status: 'draft'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        point: [{ required: true, message: 'point is required', trigger: 'blur' }],
        name: [{ required: true, message: 'name is required', trigger: 'blur' }],
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        getway: [{ required: true, message: 'way is required', trigger: 'blur' }],
        number: [{ required: true, message: 'number is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getGiftList()
  },
  methods: {
    getGiftList() {
      this.listLoading = true
      fetchGiftList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getGiftList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    // 重置temp
    resetTemp() {
      this.temp = {
        id: undefined,
        timestamp: new Date(),
        name: '',
        status: 'draft',
        selfstatus: 'preparing',
        type: '',
        getway:'',
        point:'',
        number:''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createGiftData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024
          this.temp.author = 'XinMiao_MS'
          createGift(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateGiftData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
          updateGift(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'name', 'type','getway','number', 'point', 'operator', 'operateTime','status']
        const filterVal = ['id', 'name', 'type','getway', 'number', 'point','operator', 'timestamp', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>